<script type="text/babel">
import { Spinner } from 'vue-ydui/dist/lib.rem/spinner'
export default {
  name: 'spinner',
  extends: Spinner,
  methods: {
    calculation (type) {
      const max = ~~this.max
      const min = ~~this.min < 0 ? ~~this.unit : ~~this.min
      const unit = ~~this.unit
      if (this.readonly) return
      let val = ~~this.counter
      let newval
      if (type === 'add') {
        newval = val + unit
        if (max !== 0 && newval > max) return
      } else {
        newval = val - unit
        if (newval < min) return
      }
      this.counter = newval
      this.$emit('input', newval)
      if (this.longpress) {
        this.longpressHandler(type)
      }
    },
    bindEvents () {
      const add = this.$refs.add
      const minus = this.$refs.minus
      const events = {
        mousedownEvent: 'touchstart',
        mouseupEvent: 'touchend'
      }
      const isMobile = (window.Modernizr && !!window.Modernizr.touch) || (function () {
        return !!(('ontouchstart' in window) || (window.DocumentTouch && document instanceof window.DocumentTouch))
      })()
      if (!isMobile) {
        events.mousedownEvent = 'mousedown'
        events.mouseupEvent = 'mouseup'
      }
      add.addEventListener(events.mousedownEvent, (e) => {
        if (this.longpress) {
          if (e.cancelable) {
            e.preventDefault()
          }
          e.stopPropagation()
          this.tapParams.tapStartTime = new Date().getTime() / 1000
          add.addEventListener(events.mouseupEvent, this.clearTapTimer)
        }
        this.calculation('add')
      })
      minus.addEventListener(events.mousedownEvent, (e) => {
        if (this.longpress) {
          if (e.cancelable) {
            e.preventDefault()
          }
          e.stopPropagation()
          this.tapParams.tapStartTime = new Date().getTime() / 1000
          minus.addEventListener(events.mouseupEvent, this.clearTapTimer)
        }
        this.calculation('minus')
      })
      this.$refs.numInput.addEventListener('change', (e) => {
        this.setValue(~~this.counter)
        this.$emit('input', ~~this.counter)
        this.callback(this.val, ~~this.counter)
      })
    }
  }
}
</script>
